const path = require("path");
const fs = require("fs");

function merge({ data }, callback) {
  const filename = data.filename;
  const type =
    data.type.split("/")[1] === "x-zip-compressed"
      ? "zip"
      : data.type.split("/")[1];
  const ext = "." + type;
  const fileDirectoryPath = path.resolve(__dirname, "../resources", type);
  // 检查目录是否存在，如果不存在则创建
  if (!fs.existsSync(fileDirectoryPath)) {
    console.log("目录不存在，创建目录", fileDirectoryPath);
    fs.mkdirSync(fileDirectoryPath, { recursive: true });
  }
  // 写入文件路径
  const filePath = path.resolve(
    __dirname,
    `../../resources/${type}`,
    filename + ext
  );
  // 文件切片路径
  const directortyPath = path.resolve(__dirname, "../resources", filename);
  const directorty = fs.readdirSync(directortyPath).sort((a, b) => {
    const aNum = Number(a.split("-")[1]);
    const bNum = Number(b.split("-")[1]);
    return aNum - bNum;
  });
  console.log("directorty", directorty);
  const writeStream = fs.createWriteStream(filePath);
  let count = 0;
  mergeSlice({
    writeStream,
    directortyPath,
    directorty,
    count,
    callback,
    fileInfo: {
      filename,
      ext,
      type,
    },
  });
}

// 合并文件切片 使用递归的方式，按文件顺序合并切片
function mergeSlice({
  writeStream,
  directortyPath,
  directorty,
  count,
  callback,
  fileInfo,
}) {
  console.log("mergeSlice", count);
  if (count >= directorty.length) {
    const { filename, ext, type } = fileInfo;
    writeStream.end();
    callback({
      code: 200,
      message: `${filename + ext}合并成功`,
      data: {
        url: `/resources/${type}/${filename + ext}`,
      },
    });
    // 删除切片目录
    deleteDirectoryRecursive(directortyPath);
    return;
  }
  // const index = directorty.findIndex((item) => item.includes(count));
  const rs = fs.createReadStream(
    path.resolve(directortyPath, directorty[count])
  );
  rs.pipe(writeStream, { end: false });
  rs.on("end", () => {
    // console.log(`第${count}个切片合并完成`);
    // console.log(directorty[count]);
    count++;
    mergeSlice({
      writeStream,
      directortyPath,
      directorty,
      count,
      callback,
      fileInfo,
    });
  });
  rs.on("error", (err) => {
    console.error(`读取切片文件时发生错误：${err}`);
    callback({
      code: 500,
      message: "文件合并失败！",
    });
  });
}
// 移除分片目录
function deleteDirectoryRecursive(directoryPath) {
  fs.rm(directoryPath, { recursive: true, force: true }, (err) => {
    if (err) {
      console.error("Error deleting directory:", err);
    } else {
      console.log("Directory deleted successfully");
    }
  });
}

module.exports = {
  mergeSlice,
  deleteDirectoryRecursive,
  merge,
};
